package uk.co.accolade.clash.multicast;

import com.intellij.openapi.components.ApplicationComponent;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.net.InetAddress;
import java.net.MulticastSocket;

public class ClashMulticastComponent implements ApplicationComponent {

    private static final Log LOG = LogFactory.getLog( ClashMulticastComponent.class );

    private MulticastCommunicator communicator;

    @NonNls
    @NotNull
    public String getComponentName() {
        return "ClashMulticastComponent";
    }

    public void initComponent() {
        try {
            communicator = initComms();
        } catch( IOException e ) {
            LOG.error( "Problems initialising the multicast component: " + e.getMessage(), e );
        }
    }

    public void disposeComponent() {
        communicator.stopListening();
    }

    public MulticastCommunicator getCommunicator() {
        return communicator;
    }

    private MulticastCommunicator initComms() throws IOException {
        MulticastSocket socket = new MulticastSocket(MulticastCommunicator.SOCKET_PORT);
        InetAddress group = InetAddress.getByName(MulticastCommunicator.GROUP_ADDRESS);
        MulticastCommunicator communicator = new MulticastCommunicator( socket, group );
        communicator.register();
        communicator.startListening();
        return communicator;
    }
    
}
